package net.a6polo.a6poloweibo;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.a6polo.a6poloweibo.view.MultiSpinner;
import net.a6polo.a6poloweibo.view.MultiSpinner.MultiSpinnerListener;
import net.a6polo.renren.RenrenAPIV2;
import net.a6polo.renren.RenrenApi;
import net.a6polo.renren.domain.PhotosUploadResponse;
import net.a6polo.renren.domain.ResultResponse;
import net.a6polo.service.Service;
import net.a6polo.service.SnsType;
import net.a6polo.service.domain.Account;

import com.google.gson.Gson;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.net.RequestListener;

import a6polo.net.tencen.qzone.QzoneApi;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Writeweiboactivity extends Activity implements OnClickListener,
		DialogInterface.OnClickListener {
	private static RenrenAPIV2 renrenApi ;
	private static QzoneApi qzoneApi;
	private static String content;
	private static final int ID = 1213;
	private Handler handler = null;
	private Button sendButton;
	private EditText contentTextView;
	private Button hasPic;
	private Uri imageFileUri = null;
	private static final int CAMERA_RESULT = 0;
	private static final int PIC_RESULT = 1;
	private String picPath = "";
	
	private List<String> list = new ArrayList<String>();  
	private MultiSpinner mySpinner; 
	private ArrayAdapter<String> adapter;
	private Service service;
	private Exception exception;
	private List<Integer> selectedIndexList = new ArrayList<Integer>();
	private List<Account> accountList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_writeweiboactivity);
		service = new Service(Writeweiboactivity.this);
		accountList = service.getAccounts();
		
		for(Account account : accountList) {
			StringBuffer label = new StringBuffer();
			switch (account.getType()) {
			case SnsType.RENREN:
				label.append("人人网：");
				break;
			case SnsType.SINA_WEIBO:
				label.append("新浪微博：");
				break;
			}
			label.append(account.getUserName());
			list.add(label.toString());
		}
        
        mySpinner = (MultiSpinner)findViewById(R.id.city); 
        adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_multichoice, list);
        mySpinner.setAdapter(adapter); 
        mySpinner.setItems(list, "选择微博", new MyMultiSpinnerListener());

		handler = new Handler();
		sendButton = (Button) findViewById(R.id.menu_send);
		sendButton.setOnClickListener(this);

		hasPic = (Button) findViewById(R.id.menu_add_pic);
		hasPic.setOnClickListener(this);

		contentTextView = (EditText) findViewById(R.id.status_new_content);

		Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();
		if (Intent.ACTION_SEND.equals(action) && type != null) {
			if (type.startsWith("image/")){
				handleSendImage(intent);
			}
		}
	}
	
	private void handleSendImage(Intent intent) {


        Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
        if (imageUri != null) {
            picPath = getPicPathFromUri(imageUri);
            contentTextView.setText(getString(R.string.share_pic));
        }
	}
    

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.menu_send: {
			send();
			break;
		}
		case R.id.menu_add_pic: {
			addPic();
			break;
		}
		default:
			break;
		}

	}

	public void send() {
		
		content = contentTextView.getText().toString();

		Context ctx = Writeweiboactivity.this;
//		SharedPreferences sp = ctx.getSharedPreferences("token", MODE_PRIVATE);
//		String token = sp.getString("access_token", "none");
//		String expires_in = sp.getString("expires_in", "none");
		
		
		Service service = new Service(Writeweiboactivity.this);
		
		Account sinaAccount = service.getLastAccountByType(SnsType.SINA_WEIBO);
		
		Oauth2AccessToken accessToken = new Oauth2AccessToken(sinaAccount.getAccessToken(), sinaAccount.getExpiresIn());
		StatusesAPI statusApi = new StatusesAPI(accessToken);
		
		renrenApi = new RenrenAPIV2(ctx);
		
/*		qzoneApi = new QzoneApi(ctx);
		
		 new Thread(new Runnable(){
			    @Override
			    public void run() {
			    	
			    	AddShareResponse response = qzoneApi.addShare(content, content, content, content);
					if(response.getRet().equals("0")) {
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								Toast.makeText(
										Writeweiboactivity.this,"QQ空间更新成功",
										Toast.LENGTH_LONG).show();
							}
						});
					} else {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								Toast.makeText(
										Writeweiboactivity.this,"QQ空间更新失败",
										Toast.LENGTH_LONG).show();
							}
						});
					}

			    }
		 }).start();*/

		
		if (TextUtils.isEmpty(picPath)) {
			for(Integer index : selectedIndexList) {
				Account account = accountList.get(index);
				switch (account.getType()) {
				case SnsType.RENREN:
					renrenApi.updateStatus(content, new RenrenUpdateRequestListener());
					break;
				case SnsType.SINA_WEIBO:
					statusApi.update(content, null, null, new StatusUpdateRequestListener());	
					break;
				}
			}
			
			
		} else {
			for(Integer index : selectedIndexList) {
				Account account = accountList.get(index);
				switch (account.getType()) {
				case SnsType.RENREN:
					renrenApi.photoUpload(content, picPath, new RenrenUpdatePhotoRequestListener());
					break;
				case SnsType.SINA_WEIBO:
					statusApi.upload(content, picPath, null, null, new StatusUpdateRequestListener());
					break;
				}
			}

			
//			 new Thread(new Runnable(){
//				    @Override
//				    public void run() {
//
//				        try {
//							 PhotosUploadResponse photo = renrenApi.photoUpload(content,picPath);
//							 runOnUiThread(new Runnable() {
//
//									@Override
//									public void run() {
//										addNotification("人人状态更新成功...");
//										 
//										 Toast.makeText(
//													Writeweiboactivity.this,"人人網更新成功",
//													Toast.LENGTH_LONG).show();
//									}
//								});
//							 
//						} catch (FileNotFoundException e) {
//							 	 
//							 runOnUiThread(new Runnable() {
//									@Override
//									public void run() {
//										addNotification("人人状态更新失败...");
//										 
//										 Toast.makeText(
//													Writeweiboactivity.this,"人人網更新失敗",
//													Toast.LENGTH_LONG).show();
//									}
//								});
//							 
//							e.printStackTrace();
//						}
//				    }
//			 }).start();
		}

		addNotification("正在发送微博...");

		Intent intent = new Intent();
		intent.setClass(Writeweiboactivity.this, MainTabActivity.class);
		startActivity(intent);

//		 Context ctx = Writeweiboactivity.this;		 
//		 
//		 
//		 if (TextUtils.isEmpty(picPath)) {
//			 if(renrenApi.updateStatus(content)) {
//				 addNotification("人人状态更新成功...");
//			 } else {
//				 addNotification("人人状态更新失败...");
//			 }
//		 } else {
//			 try {
//				 PhotosUploadResponse photo = renrenApi.photoUpload(content,picPath);
//				 addNotification("人人状态更新成功...");
//			} catch (FileNotFoundException e) {
//				 addNotification("人人状态更新失败...");
//				e.printStackTrace();
//			}
//		 }
		
		
		finish();
	}

	public void addPic() {

		new SelectPictureDialog().show(getFragmentManager(), "");

		/*
		 * Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW);
		 * intent.setDataAndType(Uri.fromFile(new File("/")), "image/png");
		 * PackageManager packageManager = getPackageManager();
		 * List<ResolveInfo> activities =
		 * packageManager.queryIntentActivities(intent, 0); boolean isIntentSafe
		 * = activities.size() > 0; if (isIntentSafe) { startActivity(intent); }
		 */
	}

	class StatusUpdateRequestListener implements RequestListener {

		@Override
		public void onComplete(String json) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					Toast.makeText(Writeweiboactivity.this,
							R.string.weibosdk_send_sucess, Toast.LENGTH_LONG)
							.show();

					addNotification("微博发送完成");
				}
			});
		}

		@Override
		public void onError(WeiboException e) {
			final WeiboException e1 = e;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(
							Writeweiboactivity.this,
							String.format(
									Writeweiboactivity.this
											.getString(R.string.weibosdk_send_failed)
											+ ":%s", e1.getMessage()),
							Toast.LENGTH_LONG).show();
				}
			});
		}

		@Override
		public void onIOException(IOException e) {
			final IOException e1 = e;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(
							Writeweiboactivity.this,
							String.format(
									Writeweiboactivity.this
											.getString(R.string.weibosdk_send_failed)
											+ ":%s", e1.getMessage()),
							Toast.LENGTH_LONG).show();
				}
			});
		}

	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		switch (which) {
		case 0:

			imageFileUri = getContentResolver().insert(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
					new ContentValues());
			Intent i = new Intent(
					android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
			startActivityForResult(i, CAMERA_RESULT);
			break;
		case 1:
			Intent choosePictureIntent = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(choosePictureIntent, PIC_RESULT);
			break;
		}

	}

	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);

		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CAMERA_RESULT:
				if (TextUtils.isEmpty(contentTextView.getText().toString())) {
					contentTextView.setText(getString(R.string.share_pic));
					contentTextView.setSelection(contentTextView.getText()
							.toString().length());
				}

				picPath = getPicPathFromUri(imageFileUri);
				// havePic.setVisibility(View.VISIBLE);
				break;
			case PIC_RESULT:
				if (TextUtils.isEmpty(contentTextView.getText().toString())) {
					contentTextView.setText(getString(R.string.share_pic));
					contentTextView.setSelection(contentTextView.getText()
							.toString().length());
				}

				Uri imageFileUri = intent.getData();
				picPath = getPicPathFromUri(imageFileUri);
				// havePic.setVisibility(View.VISIBLE);
				break;
			/*
			 * case AT_USER: String name = intent.getStringExtra("name"); String
			 * ori = contentTextView.getText().toString(); int index =
			 * contentTextView.getSelectionStart(); StringBuilder stringBuilder
			 * = new StringBuilder(ori); stringBuilder.insert(index, name);
			 * contentTextView.setText(stringBuilder.toString());
			 * contentTextView.setSelection(index + name.length()); break;
			 */
			}

		}
	}

	private String getPicPathFromUri(Uri uri) {
		String value = uri.getPath();

		if (value.startsWith("/external")) {
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = managedQuery(uri, proj, null, null, null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} else {
			return value;
		}
	}

	public void addNotification(String cotificationContent) {

		String service = NOTIFICATION_SERVICE;
		NotificationManager nm = (NotificationManager) getSystemService(service);
		Notification n = new Notification();
		int icon = R.drawable.msg_icon;
		String tickerText = getResources().getString(R.string.app_name);
		long when = System.currentTimeMillis();

		n.icon = icon;
		n.tickerText = tickerText;
		n.when = when;
		// n.flags = Notification.FLAG_ONGOING_EVENT;
		n.flags |= Notification.FLAG_AUTO_CANCEL;
		Intent it = new Intent(this, Writeweiboactivity.class);
		// it.putExtra(KEY_COUNT, count);

		PendingIntent pi = PendingIntent.getActivity(this, 0, it,
				PendingIntent.FLAG_UPDATE_CURRENT);

		n.setLatestEventInfo(Writeweiboactivity.this, tickerText,
				cotificationContent, pi);

		nm.notify(ID, n);
	}
	

	class MyMultiSpinnerListener implements MultiSpinnerListener{

		@Override
		public void onItemsSelected(boolean[] selected) {
			int index = 0;
			
			for(boolean bool : selected) {
				if(bool) {
					selectedIndexList.add(index);
				}
				index++;
			}
		}
	}
	
	class RenrenUpdateRequestListener implements net.a6polo.renren.net.RequestListener {
		@Override
		public void onComplete(String json) {
			Gson gson = new Gson();
			ResultResponse result = gson.fromJson(json, ResultResponse.class);
			if (result.getResult().equals("1")) {
				 runOnUiThread(new Runnable() {

						@Override
						public void run() {
							 addNotification("人人状态更新成功...");
							 Toast.makeText(
										Writeweiboactivity.this,"人人網更新成功",
										Toast.LENGTH_LONG).show();
						}
					});
			} else {
				 runOnUiThread(new Runnable() {

						@Override
						public void run() {
							 addNotification("人人状态更新失败...");
							 Toast.makeText(
										Writeweiboactivity.this,"人人網更新失败",
										Toast.LENGTH_LONG).show();
						}
					});
			}
		}

		@Override
		public void onIOException(IOException e) {
			exception = e;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), " error : " + exception.getMessage(), Toast.LENGTH_LONG)
							.show();
				}
			});
		}

		@Override
		public void onError(Exception e) {
			exception = e;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), " error : " + exception.getMessage(), Toast.LENGTH_LONG)
							.show();
				}
			});
		}
	}
	
	class RenrenUpdatePhotoRequestListener implements net.a6polo.renren.net.RequestListener {
		@Override
		public void onComplete(String json) {
			
			try{
				Gson gson = new Gson();
				gson.fromJson(json, PhotosUploadResponse.class);
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						addNotification("人人状态更新成功...");
						 
						 Toast.makeText(
									Writeweiboactivity.this,"人人網更新成功",
									Toast.LENGTH_LONG).show();
					}
				});
			} catch (Exception e) {
				exception = e;
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getApplicationContext(), " error : " + exception.getMessage(), Toast.LENGTH_LONG)
								.show();
					}
				});
			}
		}

		@Override
		public void onIOException(IOException e) {
			exception = e;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), " error : " + exception.getMessage(), Toast.LENGTH_LONG)
							.show();
				}
			});
		}

		@Override
		public void onError(Exception e) {
			exception = e;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), " error : " + exception.getMessage(), Toast.LENGTH_LONG)
							.show();
				}
			});
		}
	}

}



